package com.suxin.ratelimit.v2.aop;

import com.suxin.ratelimit.v2.RateLimit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor;
import org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Tang
 * @classname RateLimitAspect
 * @description [ 切面类 ]
 * @date 2022/2/9 16:46
 */
@Slf4j
public class RateLimitAspect {

    @Bean
    public AbstractBeanFactoryPointcutAdvisor advisor(DefaultStaticMethodMatcherPointcut matcherPointcut,
                                                      DefaultMethodInterceptor methodInterceptor) {
        DefaultBeanFactoryPointcutAdvisor advisor = new DefaultBeanFactoryPointcutAdvisor();
        advisor.setPointcut(matcherPointcut);advisor.setAdvice(methodInterceptor);
        return advisor;
    }

    @Bean
    public DefaultMethodInterceptor methodInterceptor() {
        return new DefaultMethodInterceptor();
    }

    @Component
    static class DefaultStaticMethodMatcherPointcut extends StaticMethodMatcherPointcut {
        @Override
        public boolean matches(Method method, Class<?> targetClass) {
            return method.getAnnotation(RateLimit.class) != null;
        }
    }

}